package com.example.v2.intercepter;

import com.alibaba.fastjson.JSON;
import com.example.common.enumerator.ServiceCode;
import com.example.v2.constant.JwtConstants;
import com.example.v2.response.JsonResult;
import com.example.v2.response.StatusCode;
import com.example.v2.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author Kiven
 */
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader(JwtConstants.AUTHORIZATION);
        if (header != null && header.startsWith(JwtConstants.AUTHORIZATION_BEARER)) {
            String token = header.substring(JwtConstants.AUTHORIZATION_BEARER.length());
            try {
                JWTUtil.verify(token);
            } catch (Exception e) {
                log.debug("token过期", e.getMessage());
                response.setContentType("application/json;charset=utf-8");
                response.setStatus(ServiceCode.ERROR_UNAUTHORIZED.getValue());
                response.getWriter().write(JSON.toJSONString(JsonResult.failed(StatusCode.NOT_LOGIN,"请重新登录")));
                return false;
            }
        } else {
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(ServiceCode.ERROR_UNAUTHORIZED.getValue());
            response.getWriter().write(JSON.toJSONString(JsonResult.failed(StatusCode.NOT_LOGIN,"请登录后访问")));
            return false;
        }

        return true;
    }
}
